package cn.afterturn.easypoi.util;


import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;

import static org.junit.Assert.assertTrue;

/**
 *MD5计算工具
 */
public class MD5 {
    /**
     * 获取该文件的MD5值
     *
     * @param file
     * @return
     * @throws
     * @throws IOException
     */
    public static String getMD5Ex(File file) throws Exception {
        FileInputStream fis = new FileInputStream(file);
        return getMD5(fis);
    }
    /**
     * 获取该输入流的MD5值
     *
     * @param is
     * @return
     * @throwsrr
     * @throws IOException
     */
    public static String getMD5(InputStream is) throws Exception {
        StringBuffer md5 = new StringBuffer();
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] dataBytes = new byte[1024];

        int nread = 0;
        while ((nread = is.read(dataBytes)) != -1) {
            md.update(dataBytes, 0, nread);
        };
        byte[] mdbytes = md.digest();

        // convert the byte to hex format
        for (int i = 0; i < mdbytes.length; i++) {
            md5.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
        }
        return md5.toString();
    }

    /**
     * 获取一个文件的md5值(可处理大文件)
     * @return md5 bookmarkvalue
     */
    public static String getMD5(File file) {
        FileInputStream fileInputStream = null;
        try {
            MessageDigest MD5 = MessageDigest.getInstance("MD5");
            fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
                MD5.update(buffer, 0, length);
            }
            return new String(Hex.encodeHex(MD5.digest()));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (fileInputStream != null){
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 求一个字符串的md5值
     * @param target 字符串
     * @return md5 bookmarkvalue
     */
    public static String MD5(String target) {
        return DigestUtils.md5Hex(target);
    }

    public static void main(String[] args) throws Exception{
        long beginTime = System.currentTimeMillis();
        File file = new File("D:/tt.docx");
        String md5 = getMD5(file);
        long endTime = System.currentTimeMillis();
        System.out.println("MD5:" + md5 + "\n 耗时:" + ((endTime - beginTime) / 1000) + "s");

        String md5x=getMD5Ex(file);
        System.out.println("MD5x:" + md5x + "\n 耗时:" + ((endTime - beginTime) / 1000) + "s");
        assertTrue(md5.equals(md5x));


    }
}